#include "uds.h"
#include "main.h"
#include "can.h"
#include <string.h>
#include <stdio.h>

extern CAN_HandleTypeDef hcan2;

uint8_t rx_buffer[4096];
uint16_t rx_len = 0;
uint16_t rx_total = 0;
uint8_t rx_sn = 1;
uint8_t receiving = 0;


/// @brief 自动分帧发送 UDS 请求（支持SF与FF+CF）
static void isotp_send_request(uint8_t *data, uint16_t len) {
    if (len <= 7) {
        uint8_t sf[8] = {0x00 | len};
        memcpy(&sf[1], data, len);
        can2_send_msg(0x731, sf, 8);
        return;
    }

    // 发送 FF（First Frame）
    uint8_t ff[8];
    ff[0] = 0x10 | ((len >> 8) & 0x0F);
    ff[1] = len & 0xFF;
    memcpy(&ff[2], data, 6);
    can2_send_msg(0x731, ff, 8);

    HAL_Delay(1); // 延时等待 FC帧，当前简化为1ms固定等待

    // 发送 CF（Consecutive Frame）
    uint16_t offset = 6;
    uint8_t sn = 1;
    while (offset < len) {
        uint8_t cf[8];
        cf[0] = 0x20 | (sn & 0x0F);
        uint8_t chunk = (len - offset > 7) ? 7 : (len - offset);
        memcpy(&cf[1], &data[offset], chunk);
        for (uint8_t i = 1 + chunk; i < 8; i++) cf[i] = 0x00;
        can2_send_msg(0x731, cf, 8);
        offset += chunk;
        sn = (sn + 1) & 0x0F;
        HAL_Delay(1);
    }
}



void UDS_Tester_Init(void) {
    HAL_CAN_Start(&hcan2);
		HAL_CAN_ActivateNotification(&hcan2 ,CAN_IT_RX_FIFO0_MSG_PENDING);
}

void UDS_Request_Session(void) {
    uint8_t payload[] = {0x10, 0x01};
    isotp_send_request(payload, sizeof(payload));
    printf("Sent 0x10 01\r\n");
}


void UDS_Poll(void) {
    // 可扩展
}
